package com.yt.order.api.cms;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import com.yt.order.models.service.IWorkOrderInfoService;
import com.yt.order.models.bo.WorkOrderInfoSaveBO;
import com.yt.order.models.bo.WorkOrderInfoBO;
import com.yt.order.models.dto.WorkOrderInfoDTO;

/**
 * 工单控制器
 *
 * @author xieyanfei
 * @Date 2025-09-04 21:53:07
 */

@RestController
@RequestMapping("/cms/workOrderInfo")
@Slf4j
@Api(value = "WorkOrderInfoController", tags = "工单接口")
public class WorkOrderInfoController {

    @DubboReference
    private IWorkOrderInfoService workOrderInfoService;

    @ApiOperation(value = "添加工单", notes = "添加工单")
    @PostMapping(value = "/insert")
    public Result insert(WorkOrderInfoSaveBO saveBO) {
        boolean flag = workOrderInfoService.add(saveBO);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存工单", notes = "保存工单（新增或更新）")
    public Result save(WorkOrderInfoSaveBO saveBO) {
        if (saveBO.getId() == null) {
            // 新增
            return insert(saveBO);
        } else {
            // 更新
            return update(saveBO);
        }
    }

    @ApiOperation(value = "修改工单", notes = "修改工单")
    @PostMapping("/update")
    public Result update(WorkOrderInfoSaveBO saveBO) {
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        boolean flag = workOrderInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改工单状态", notes = "单独修改工单的状态字段")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "工单状态", required = true, paramType = "query", dataType = "Integer")
    })
    public Result updateStatus(Long id, Integer status) {
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        dto.setId(id);
        dto.setStatus(status);
        boolean flag = workOrderInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @ApiOperation(value = "删除工单", notes = "根据ID删除工单")
    @ApiImplicitParam(name = "id", value = "工单ID", required = true, paramType = "query", dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id) {
        boolean flag = workOrderInfoService.deleteById(id);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除工单", notes = "根据ID列表批量删除工单")
    @ApiImplicitParam(name = "ids", value = "工单ID列表（以逗号隔开）", required = true, paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids) {
        if (StrUtils.isEmpty(ids)) {
            return new Result(CodeEnum.FAIL_100002);
        }
        String[] idArray = ids.split(",");
        workOrderInfoService.deleteBatchIds(Arrays.asList(idArray));
        return new Result<>();
    }

    @PostMapping("/get")
    @ApiOperation(value = "查询工单详情", notes = "根据ID查询工单详细信息")
    @ApiImplicitParam(name = "id", value = "工单ID", required = true, paramType = "query", dataType = "Long")
    public Result<WorkOrderInfoDTO> get(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        WorkOrderInfoDTO dto = workOrderInfoService.selectById(id);
        return new Result<>(dto);
    }

    @ApiOperation(value = "工单列表", notes = "分页查询工单列表，支持按状态、时间范围筛选")
    @PostMapping("/queryPageList")
    public Result<Page<WorkOrderInfoDTO>> queryPageList(@RequestBody WorkOrderInfoBO bo) {
        // 校验分页参数
        if (bo.getPageNo() == null || bo.getPageSize() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();

        // 状态筛选
        if (bo.getStatus() != null) {
            wrapper.eq("status", bo.getStatus());
        }

        // 时间范围筛选（创建时间）
        if (bo.getStartDate() != null) {
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null) {
            wrapper.le("create_time", bo.getEndDate());
        }

        // 分页查询
        int pageNo = bo.getPageNo() == null ? 1 : bo.getPageNo();
        int pageSize = bo.getPageSize() == null ? 10 : bo.getPageSize(); // 默认每页10条
        Page<WorkOrderInfoDTO> page = new Page<>(pageNo, pageSize);
        page = workOrderInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    /**
     * 新增：工单状态变更为进行中（未派单→进行中）
     */
    @PostMapping("/changeToInProgress")
    @ApiOperation(value = "工单状态变更为进行中", notes = "仅允许从'未派单'状态变更为'进行中'")
    @ApiImplicitParam(name = "id", value = "工单ID", required = true, paramType = "query", dataType = "Long")
    public Result changeToInProgress(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        boolean flag = workOrderInfoService.changeToInProgress(id);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    /**
     * 新增：工单拒绝接口
     */
    @PostMapping("/reject")
    @ApiOperation(value = "拒绝工单", notes = "拒绝工单并记录原因")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "reason", value = "拒绝原因", required = true, paramType = "query", dataType = "String")
    })
    public Result reject(@RequestParam("id") Long id, @RequestParam("reason") String reason) {
        if (id == null || StrUtils.isEmpty(reason)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        boolean flag = workOrderInfoService.rejectOrder(id, reason);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }
}